﻿using System;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;

namespace MetroNextTools.NHelper
{
    /// <summary>
    /// UI线程辅助类
    /// 即可以在UI线程同步执行也可以异步执行
    /// </summary>
    public static class UIDispatcher
    {
        private static CoreDispatcher dispatcher;

        public static void Initialize()
        {
            dispatcher = Window.Current.Dispatcher;
        }

        /// <summary>
        /// 异步执行
        /// </summary>
        /// <param name="action"></param>
        public static void BeginExecute(Action action)
        {
            if (dispatcher.HasThreadAccess)
            {
                action();
            }
            else
            {
                dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
            }
        }

        /// <summary>
        /// 同步执行
        /// </summary>
        /// <param name="action"></param>
        public static void Execute(Action action)
        {
            InnerExecute(action).Wait();
        }
        
        private static async Task InnerExecute(Action action )
        {
            if(dispatcher.HasThreadAccess) {
                action();
            } else{
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal,()=>action());
            }
        }
    }
}
